package com.csscaps.auth.controller;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.csscaps.auth.model.SysOrg;
import com.csscaps.auth.service.SysOrgService;
import com.csscaps.system.base.BaseTreeNode;
import com.csscaps.system.utils.Constants;
import com.csscaps.system.utils.ResultUtil;
import com.csscaps.system.utils.UUIDGenerator;
import com.github.pagehelper.PageInfo;

 /**
 * @file  SysOrgcontroller.java
 * @author wanglei
 * @version 0.1
 * @todo	TODO
 * Copyright(C), 2015
 *			xi'an Coordinates Software Development Co., Ltd.
 * History
 *   	1. Date: 2016-07-23 04:37:01
 *      	Author: wanglei
 *      	Modification: this file was created
 *   	2. ...
 */
@Controller
@RequestMapping(value="/SysOrg") 
public class SysOrgController{
    private final Log log = LogFactory.getLog(SysOrgController.class);
   
	final String zero="0";
	final String twozero="00";
	final String newFirstCode="001";
	@Autowired
	private SysOrgService sysOrgService;


		/**
	 * 新增
	 * @return
	 */
	@RequestMapping(value = "add" , method=RequestMethod.POST)
	@ResponseBody
	public Map  add(@Valid  @RequestBody SysOrg vo){
		
		Map resoultMap = null;
		try {
			vo.setOrgCreateTime(new Date());
			vo.setOrgUuid(UUIDGenerator.genUuidStr());
			vo.setDeleteStatus(Constants.NOT_DELETED);
			/*如果是根节点，直接赋值*/
			if(vo.getOrgParentUuid()==null)
			{
				vo.setOrganizationCode(newFirstCode);
			}
			/*如果不是根节点，取父节点code并查询相邻节点code*/
			else{
				String parentCode = sysOrgService.selectByPk(vo.getOrgParentUuid()).getOrganizationCode();
				List <SysOrg> list = sysOrgService.getCode(parentCode);
				String newCode;
				if (list.size()>0){
					SysOrg adjacent = list.get(0);
					String adjacentCode=adjacent.getOrganizationCode();
					String lastCode = adjacentCode.substring(adjacentCode.length()-3,adjacentCode.length());
					/*根据相邻节点code得到新增节点code*/
					int i = Integer.parseInt(lastCode)+1;
					lastCode = Integer.toString(i);
					if(lastCode.length() == 1){
						lastCode=twozero+lastCode;
					}
					if(lastCode.length() == 2){
						lastCode=zero+lastCode;
					}
					newCode=parentCode+lastCode;
				}
				else{
					newCode=parentCode+newFirstCode;
				}
				vo.setOrganizationCode(newCode);
			}
			sysOrgService.insertByVo(vo);
			resoultMap = ResultUtil.getSuccessResult();
		} catch (Exception e) {
			e.printStackTrace();
			resoultMap = ResultUtil.getErrorResult();
		}
		
		return resoultMap;
	}
	
	
	/**
	 * 修改
	 * @return
	 */
	@RequestMapping(value = "edit", method=RequestMethod.POST)
	@ResponseBody
	public Map  edit(@Valid  @RequestBody SysOrg vo){
		
		Map resoultMap = null;
		try {
			sysOrgService.updateByVO(vo);
			resoultMap = ResultUtil.getSuccessResult();
		} catch (Exception e) {
			e.printStackTrace();
			resoultMap = ResultUtil.getErrorResult();
		}
		
		return resoultMap;
	}
	/**
	 * 删除
	 * @return
	 */
	@RequestMapping(value = "remove", method=RequestMethod.POST)
	@ResponseBody
	public Map  remove(@Valid  @RequestBody SysOrg vo){
		
		Map resoultMap = null;
		try {
			sysOrgService.deleteByVo(vo);
			resoultMap = ResultUtil.getSuccessResult();
		} catch (Exception e) {
			e.printStackTrace();
			resoultMap = ResultUtil.getErrorResult();
		}
		
		return resoultMap;
	}
	
	
	/**
	 * 查询所有机构
	 * @return
	 */
	@RequestMapping(value = "getAll")
	@ResponseBody
	public Map  getAll(){
		
		Map resoultMap = null;
		List<Object>  organizationNodeList = new ArrayList<Object>() ;
		try {
		 
			List<SysOrg> list =	sysOrgService.selectAll();
			for(int i = 0; i<list.size();i++){
  				SysOrg SysOrg = list.get(i);
  				BaseTreeNode treeNode = new BaseTreeNode();
  				treeNode.setId(SysOrg.getOrgUuid());
  				treeNode.setpId(SysOrg.getOrgParentUuid());
  				treeNode.setName(SysOrg.getOrgName());
  				organizationNodeList.add(treeNode);

  			}
			resoultMap = ResultUtil.getSuccessResult(organizationNodeList);
		} catch (Exception e) {
			e.printStackTrace();
			resoultMap = ResultUtil.getErrorResult();
		}
		
		return resoultMap;
	}

	 
 
	/**
	 * 根据条件查询
	 * @return
	 */
	@RequestMapping(value = "get", method=RequestMethod.POST)
	@ResponseBody
	public Map  get(SysOrg vo){
		
		Map resoultMap = null;
		try {
			List<SysOrg> list =	sysOrgService.selectByVo(vo);
			resoultMap = ResultUtil.getSuccessResult(list);
		} catch (Exception e) {
			e.printStackTrace();
			resoultMap = ResultUtil.getErrorResult();
		}
		
		return resoultMap;
	}
	
	/**
	 * 根据条件查询
	 * @return
	 */
	@RequestMapping(value = "getOrgChild")
	@ResponseBody
	public Map  getChild(){
		
		Map resoultMap = null;
		SysOrg vo = new SysOrg();
		try {
//			Session session = SecurityUtils.getSubject().getSession();
//			SysUser user = (SysUser)session.getAttribute("user");
//			if(user != null){
//				SysOrg sysOrg = sysOrgService.selectByPk(user.getUserOrgUuid());
//				vo.setOrganizationCode(sysOrg.getOrganizationCode());
//			}
			vo.setOrganizationCode("001");
			if(!StringUtils.isEmpty(vo.getOrganizationCode())){
				
				List<SysOrg> list =	sysOrgService.getChild(vo);
				if(list.size() > 0){
					int c = list.get(0).getOrganizationCode().length();
					for(SysOrg em:list){
						if(em.getOrganizationCode().length() == c + 3){
							em.setOrgName("  " + em.getOrgName());
						}
						if(em.getOrganizationCode().length() == c + 6){
							em.setOrgName("    " + em.getOrgName());
						}
						if(em.getOrganizationCode().length() == c + 9){
							em.setOrgName("      " + em.getOrgName());
						}
						if(em.getOrganizationCode().length() == c + 12){
							em.setOrgName("        " + em.getOrgName());
						}
					}
				}

				resoultMap = ResultUtil.getSuccessResult(list);
			}

		} catch (Exception e) {
			e.printStackTrace();
			resoultMap = ResultUtil.getErrorResult();
		}
		
		return resoultMap;
	}
	
	
	/**
	 * 分页查询
	 * @return
	 */
	@RequestMapping(value = "getOrgPage", method=RequestMethod.POST)
	@ResponseBody
	public Map  getPage(@RequestBody SysOrg vo){
		
		Map resoultMap = null;
		try {
			
			PageInfo<SysOrg> pageInfo =	sysOrgService.selectPage(vo);
			resoultMap = ResultUtil.getSuccessResult(pageInfo);
		} catch (Exception e) {
			e.printStackTrace();
			resoultMap = ResultUtil.getErrorResult();
		}
		
		return resoultMap;
	}
	
	/**
	 * 删除组织信息
	 * @return
	 */
	@RequestMapping(value = "remove/{orgUuid}", method=RequestMethod.GET)
	@ResponseBody
	public Map  removeByPk(@PathVariable ("orgUuid") String  orgUuid){
		Map resoultMap = null;
		try {
			SysOrg	sysOrg = new SysOrg();
			sysOrg.setOrgParentUuid(orgUuid);
			List<SysOrg> list = sysOrgService.selectByVo(sysOrg);
			  if(list.size()==0){
					 //删除组织信息
				  sysOrgService.deleteByPk(orgUuid);
					resoultMap = ResultUtil.getSuccessResult();
				}else{
					resoultMap = ResultUtil.getErrorResult("该结构有子结构，请先删除子结构！");
				}
			} catch (Exception e) {
			e.printStackTrace();
			resoultMap = ResultUtil.getErrorResult();
		}
		return resoultMap;
	}
	
	/**
	 * 根据id 查询
	 * @return
	 */
	@RequestMapping(value = "getByPk/{orgUuid}", method=RequestMethod.GET)
	@ResponseBody
	public Map  getByPk(@PathVariable ("orgUuid") String  orgUuid){
		Map resoultMap = null;
		try {
			 SysOrg sysOrg = sysOrgService.selectByPk(orgUuid) ;
			 resoultMap = ResultUtil.getSuccessResult(sysOrg);
			} catch (Exception e) {
			e.printStackTrace();
			resoultMap = ResultUtil.getErrorResult();
		}
		return resoultMap;
	}
	
}
